<template>
    <a-select :size="option.size" :mode="mode" :placeholder="option.placeholder" :allowClear="option.allowClear" :disabled="readonly"
        v-model:value="SelectValue">
        <a-select-option v-for="item in Dict" :key="item.value" :value="item.value">
            {{ item.label }}
        </a-select-option>
    </a-select>
</template>
<script setup>
import { watchEffect, ref, watch, inject, getCurrentInstance } from 'vue';
import { FormatIsbyteSelectValue, FormatIsbyteFormValue, FormatDictWithOption } from '../util/index'

const proxy = getCurrentInstance();
const emit = defineEmits(['UpdateEvent'])
const props = defineProps(['option', 'Value']);

const readonly = ref(false);

watchEffect(() => {
    readonly.value = !!props.option.readonly
})

const SelectValue = ref();

const GetDict = inject('GetDict')
const UpdateSelectDict = inject('UpdateSelectDict');
const SetSelectItemMapping = inject('SetSelectItemMapping');

const mode = ref('');
const Dict = ref([]);

SetSelectItemMapping(props.option.key, proxy)


watch(() => props.Value[props.option.key], val => {
    if (props.option.isbyte) {
        mode.value = 'multiple';
        SelectValue.value = FormatIsbyteSelectValue(val, Dict.value)
    } else {
        mode.value = '';
        SelectValue.value = val
    }
}, { immediate: true });

watch(SelectValue, (val) => {
    if (props.option.isbyte) {
        emit('UpdateEvent', props.option.key, FormatIsbyteFormValue(val));
    } else {
        emit('UpdateEvent', props.option.key, val);
    }
    UpdateSelectDict(props.option.key, val);
}, { deep: true })


if (Array.isArray(props.option.Dict)) {
    Dict.value = FormatDictWithOption(props.option.Dict, props.option.DictOption);;
} else {
    const DictKey = props.option.Dict.split(':');
    if (DictKey.length == 1) {
        GetDict(DictKey[0]).then(res => {
            Dict.value = FormatDictWithOption(res, props.option.DictOption);;
            SelectValue.value = FormatIsbyteSelectValue(props.Value[props.option.key], Dict.value)
        })
    }
}

const GetValueObject = () => {
    var _Object = {};
    for (let i = 0; i < Dict.value.length; i++) {
        const element = Dict.value[i];
        if (element.value == SelectValue.value) {
            _Object = element
            break;
        }
    }
    return _Object;
}

const SetDictValue = (res, value) => {
    Dict.value = res || [];
    SelectValue.value = value;
}

defineExpose({
    GetValueObject,
    SetDictValue
})

</script>
<style lang="less" scoped></style>